<template>
  <el-container>
    <el-main class="main-box">
  <el-table :data="filteredBooks" class="book-table">
    <!-- 展开列，显示书籍详细信息 -->
    <el-table-column type="expand">
      <template #default="scope">
        <div class="book-details">
          <div class="book-box">
          <img :src="scope.row.cover_url" alt="封面" class="book-cover" @click="goToBook(scope.row.id)">
          <div><strong>书名：</strong>{{ scope.row.name }}</div>
          <div><strong>发布时间：</strong>{{ scope.row.time_published }}</div>
          <div><strong>最新更新时间：</strong>{{ scope.row.time_updated }}</div>
          <div><strong>书籍总字数：</strong>{{ scope.row.word_count }} 字</div>
          <div><strong>简介：</strong>{{ scope.row.description }}</div>
          </div>
        </div>
      </template>
    </el-table-column>
    <el-table-column label="作品序号" prop="index">
      <template #default="scope">{{ scope.$index + 1 }}</template>
    </el-table-column>
    <el-table-column prop="name" label="作品名"></el-table-column>
    <el-table-column label="最新章节">
      <template #default="scope">
        {{ scope.row.chapter.length ? scope.row.chapter[scope.row.chapter.length - 1].title : '无' }}
      </template>
    </el-table-column>
    <el-table-column prop="hot_number" label="作品热度" sortable></el-table-column>
    <el-table-column align="right">
      <template #header>
        <el-input v-model="search" placeholder="输入书名进行检索" />
      </template>
      <template #default="scope">
        <div class="edit-box" v-if="Username==writer_account">
          <el-button size=small type="primary" @click="handleEdit(scope.$index, scope.row)">修改章节</el-button>
          <el-button size=small type="primary" @click="handleBook(scope.$index, scope.row)">修改作品</el-button>
        </div>
      </template>
    </el-table-column>
  </el-table>
      <!-- 编辑章节对话框组件 -->
        <el-dialog :model-value="isEditChapterDialogVisible" title="编辑章节" width="50%"
        @close="resetEditDialog"
        :before-close="beforeClose"
        >
        <div class="select-box">
        <el-button @click="addNewChapter">新建章节</el-button>
        <el-select v-model="selectedChapter"  value-key="chapter_index" placeholder="选择章节" class="chapter-select"  @change="fetchChapterDetails">
          <el-option v-for="chapter in currentBook.chapter" :key="chapter.chapter_index" :label="`第${chapter.chapter_index}章`" :value="chapter"></el-option>
        </el-select>
        
        </div>
        <el-form ref="editFormRef" :model="selectedChapter" :rules="rules" class="form-box" v-if="selectedChapter">
        <el-form-item  prop="title" label="章节标题:">
          <el-input v-model="selectedChapter.title" placeholder="章节标题"></el-input>
        </el-form-item>
        <el-form-item  prop="content" label="章节内容:">
          <el-input type="textarea" v-model="selectedChapter.content" placeholder="编辑章节内容" :rows="10" resize="none"></el-input>
        </el-form-item>
        <el-form-item>
          <el-upload
            
            class="upload-demo"
            ref="uploadRef"
            :before-upload="beforeFileUpload"
            :on-change="handleChange"
            :on-exceed="handleExceed"
            :auto-upload="false"
            :limit="1"> <el-button size="small" type="primary">上传章节文件</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <span slot="footer" class="dialog-footer">
            <el-button  type="primary" @click="saveChanges">完成</el-button>
            <el-button  v-if="selectedChapter.chapter_index <=chapterlength" type="danger" @click="deleteChapter">删除章节</el-button>
          </span>
        </el-form-item>
        </el-form>
        </el-dialog>
        <!-- 补充代码 -->
        <el-dialog :model-value="isEditBookDialogVisible" title="编辑书籍" width="50%" :before-close="beforeCloseBookDialog" @close="restBookForm">
        <el-form :model="currentBook" :rules="bookRules" ref="bookFormRef" label-width="100px">
          <el-form-item label="作品名称：" prop="name">
            <el-input v-model="currentBook.name"></el-input>
          </el-form-item>
          <el-form-item label="作品简介：" prop="description">
            <el-input type="textarea" v-model="currentBook.description" show-word-limit maxlength="120" rows="4" resize="none"></el-input>
          </el-form-item>
          <el-form-item label="作品类型：" prop="type">
            <el-radio-group v-model="currentBook.type">
              <el-radio label="男生">男生向</el-radio>
              <el-radio label="女生">女生向</el-radio>
            </el-radio-group>
          </el-form-item>
        <!-- 标签选择 -->
        <el-form-item label="标签选择：" prop="workCategories">
          <!-- 多选标签 -->
          <div class="tag-group">
            <!-- 循环显示标签选项 -->
          <el-tag
              v-for="(tag, index) in currentBook.tag"
              :key="index"
              closable
              @click="handleChecks(tag)"
              :class="{ active: tag.checked }"
              effect="plain"
              @close="handleClose(tag)"
            >
              {{ tag.labelName.length > 5 ? tag.labelName.substring(0, 5) + '...' : tag.labelName }}
            </el-tag>
          </div>
        </el-form-item>

        <!-- 自定义标签输入框 -->
        <el-form-item prop="customTagInput">
          <el-input
            placeholder="自定义标签(最多可输入6个字符)"
            maxlength="6"
            v-model="customTagInput"
          >
            <!-- 添加按钮 -->
            <template #append>
              <el-button @click="addCustomLabel(customTagInput)">添加</el-button>
            </template>
          </el-input>
        </el-form-item>

          <el-form-item label="上传新封面：" prop="cover">
            <el-upload class="avatar-uploader" list-type="picture-card" :auto-upload="false" accept="image/jpeg,image/gif,image/png" :on-change="handleCoverChange" :on-remove="handleRemove" limit="1" :file-list="bookFile">
            </el-upload>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitBookForm">修改</el-button>
          <el-button type="danger" @click="confirmDelete(currentBook)">删除作品</el-button>
        </span>
      </el-dialog>
    </el-main>
  </el-container>
</template>

<script setup>
import { ref, computed, watch,onMounted,getCurrentInstance, Suspense} from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';
import { getBooks_by_write,books } from '@/apis/getBooks_by_writer.js'
import  EditChapterDialog from './editChapter.vue'
import  EditBookDialog from './editWork.vue'
import moment from 'moment'
import axios from 'axios';
import {useRoute} from 'vue-router'


const goToBook = (bookId) => {

    router.push({ name: 'BookDetail', params: { id: bookId } });
  
};

const route = useRoute();
const writer_account=computed(() => route.params.username);
const Username = ref(localStorage.getItem('account'));

const emit=defineEmits('update:bookcount');

watch(() => books.value.length, (newLength, oldLength) => {
  // Emit the new length to the parent component
  emit('update:bookcount', newLength);
});


const props=defineProps({
  isCreate:Boolean,
  
})
watch(() => props.isCreate, (newVal) => {
      getBooks_by_write(localStorage.getItem('account'), proxy)
});
const {proxy}=getCurrentInstance();
const router = useRouter();

// 定义书籍列表的响应式数据
const search = ref('');
// 用于控制编辑对话框和上传对话框的显示
const isEditChapterDialogVisible = ref(false)
const isEditBookDialogVisible=ref(false)

const currentBook = ref(null);
const initialBookState = ref(null)
const bookFormRef=ref()
const rules = {
  title: [{ required: true, message: '章节标题不能为空', trigger: 'blur' }],
  content: [{ required: true, message: '章节内容不能为空', trigger: 'blur' }]
};

const bookRules = {
  name: [{ required: true, message: '作品名称不能为空', trigger: 'blur' }],
  description: [{ required: true, message: '作品简介不能为空', trigger: 'blur' }],
  type: [{ required: true, message: '必须选择作品类型', trigger: 'blur' }],
  workCategories: [
    {required: true, validator: (rule, value, callback) => {
      // Check if any tag is checked
      const anyChecked = currentBook.value.tag.some(tag => tag.checked);
      if (!anyChecked) {
        callback(new Error('至少选择一个作品标签'));
      } else {
        callback();
      }
    }, trigger: 'change' }
  ],
  customTagInput:[
    {max:6,message:'标签字数不多于6个',trigger:['change','blur']}
  ],
};

// 实现书籍搜索
const filteredBooks = computed(() => {
  const sanitizedSearch = search.value.replace(/\s+/g, '').toLowerCase();
  return books.value.filter(book => 
    book.name.replace(/\s+/g, '').toLowerCase().includes(sanitizedSearch)
  );
});
// 打开编辑章节的dialog
const handleEdit = (index, book) => {
  currentBook.value = book;
  chapterlength.value=currentBook.value.chapter.length
  isEditChapterDialogVisible.value = true;
};
const chapterlength=ref(0)

// 打开编辑书籍的dialog
const handleBook = (index, book) => {
  currentBook.value = {...book};
  currentBook.value.tag = currentBook.value.tag.map(tag => ({ labelName: tag, checked: true }));
  initialBookState.value = {...book}; 
  initialBookState.value.tag = initialBookState.value.tag.map(tag => ({ labelName: tag, checked: true }));
  isEditBookDialogVisible.value = true;
};

const selectedChapter = ref(null);
const editFormRef = ref(null);
const fail=ref(true)
const isAddingNewChapter=ref(false)

//重置表单信息
const beforeClose=()=>{
  isEditChapterDialogVisible.value=false;
}
const beforeCloseBookDialog = () => {
  isEditBookDialogVisible.value = false;
};

const resetEditDialog = () => {
  if(fail.value){
    const index = currentBook.value.chapter.indexOf(selectedChapter.value);
    if (index !== -1) {
      currentBook.value.chapter.splice(index, 1);
    }
  }
  fail.value=true
  isAddingNewChapter.value=false
  selectedChapter.value=null
  getBooks_by_write(localStorage.getItem('account'),proxy)
};
const restBookForm=()=>{
   document.querySelector('.el-upload').style.display='block';
   bookFile.value = [];
   getBooks_by_write(localStorage.getItem('account'),proxy)
}
const fetchChapterDetails = async (chapter) => {
    await proxy.$http.get(`/api/book/chapter?book_id=${currentBook.value.id}&chapter_index=${selectedChapter.value.chapter_index}`).then(response=>{
        selectedChapter.value.content = response.data.data.content;
    })
};

//增加的章节向后端发送请求
const saveChanges = async() => {
  // 先验证表单
  await editFormRef.value.validate(async (valid) => {
    if (valid) {
        if (selectedChapter.value.chapter_index <= chapterlength.value) {
          const formData = new FormData();
          formData.append('chapter_id', selectedChapter.value.id);
          formData.append('new_content', selectedChapter.value.content);
          
          await proxy.$http.post("/api/book/update-chapter", formData, {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          }).then(response=>{
              fail.value = false;
              isAddingNewChapter.value = false;
              ElMessage.success("修改章节成功");
          }).catch(err=>{
            ElMessage.error(err)
          });
        }else{
        // 创建一个 FormData 对象
          
          const formData = new FormData();
          formData.append('id', currentBook.value.id);
          formData.append('chapter_index', selectedChapter.value.chapter_index);
          formData.append('content', selectedChapter.value.content);
          formData.append('title', selectedChapter.value.title);
          // 使用 FormData 发送请求
          await proxy.$http.post("/api/book/upload-chapter", formData, {
            headers: {
              'Content-Type': 'multipart/form-data' // 设置请求头
            }
          }).then(response=>{
              fail.value=false
              isAddingNewChapter.value=false
              ElMessage.success(response.data)
          }).catch(err=>{
              ElMessage.error(err)
          });
        }
    } else {
      ElMessage.error('表单有误');
    }
  });
};
//删除已有章节
const deleteChapter = async () => {
  try {
    const maxChapterIndex = Math.max(...currentBook.value.chapter.map(c => c.chapter_index));

    // Check if the selected chapter has the maximum index
    if (selectedChapter.value.chapter_index !== maxChapterIndex) {
      ElMessage.error('只能删除最新的章节');
      return;
    }

    const formData = new FormData();
    formData.append('book_id', currentBook.value.id);
    formData.append('chapter_id', selectedChapter.value.id);
    await proxy.$http.post("/api/book/delete-chapter", formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    }).then(response => {
      const index = currentBook.value.chapter.indexOf(selectedChapter.value);
      if (index !== -1) {
        currentBook.value.chapter.splice(index, 1);
      }
      selectedChapter.value = null;
      ElMessage.success('章节删除成功');
    }).catch(error => {
      ElMessage.error(`删除章节失败: ${error.message}`);
    });
  } catch (error) {
    ElMessage.error(`删除章节失败: ${error.message}`);
  }
};


const beforeFileUpload = (file) => {
  const isLt500KB = file.size / 1024 < 500; // Convert size to KB and check if it's less than 500 KB
  if (!isLt500KB) {
    ElMessage.error('上传文件大小不能超过 500KB');
    return false;  // Prevent the file from being uploaded
  }
  return true;  // Allow the upload
};
//只能上传txt文档
const handleChange=(file)=> {
	  let reader = new FileReader();   //先new 一个读文件的对象 FileReader
	  const blob = new Blob([file.raw], { type: file.raw.type});
    console.log('222222222222',blob)
    reader.readAsText(blob, "UTF-8")
	  reader.onload = (evt) => {
        selectedChapter.value.content=evt.target.result
    }
}
const uploadRef=ref()
const handleExceed = (files) => {
  uploadRef.value.clearFiles()
  uploadRef.value.handleStart(files[0])
 
}
//增添新章节
const addNewChapter = () => {
  if (isAddingNewChapter.value) {
    ElMessage.warning('请先保存当前章节再添加新章节');
    return;
  }
  if (!currentBook.value || !currentBook.value.chapter) {
    ElMessage.error('无法添加新章节，未选择书籍或书籍数据有误');
    return;
  }
  const newChapterIndex = currentBook.value.chapter.length + 1; 
  const newChapter = {
    chapter_index: newChapterIndex,  
    title: '',   
    content:'',
  };
  
  currentBook.value.chapter.push(newChapter);
  isAddingNewChapter.value=true
  selectedChapter.value = newChapter;
};

const bookFile=ref()

const handleCoverChange = (file, fileList) => {
  bookFile.value=fileList
  document.querySelector('.el-upload').style.display = 'none';
};
const handleRemove = (file, fileList) => {
  document.querySelector('.el-upload').style.display = 'block';
};


const customTagInput=ref()
const handleChecks = (tag) => {
  tag.checked = !tag.checked;
};

const handleClose = (tag) => {
  if (currentBook.value.tag.length > 1) {
    currentBook.value.tag = currentBook.value.tag.filter(t => t !== tag);
  }
};

const addCustomLabel = (val) => {
  if (val && !currentBook.value.tag.some(tag => tag.labelName === val)) {
    currentBook.value.tag.push({ labelName: val, checked: true });
    customTagInput.value = '';
  }
};

const tagsChanged = () => {
  const initialTags = initialBookState.value.tag.map(tag => tag.labelName + ':' + tag.checked).sort().join('||');
  const currentTags = currentBook.value.tag.map(tag => tag.labelName + ':' + tag.checked).sort().join('||');
  return initialTags !== currentTags;
};

// 修改作品基本信息
const submitBookForm = async () => {
  await bookFormRef.value.validate(async (valid) => {
    if (valid) {
        const formData = new FormData();
        let flag=false;
        ['name', 'description', 'type'].forEach(field => {
        if (currentBook.value[field] !== initialBookState.value[field]) {
          formData.append(field,currentBook.value[field])
          flag=true
        }
        });
      if (tagsChanged()) {
        const tagsToSubmit = currentBook.value.tag.filter(tag => tag.checked).map(tag => tag.labelName).join('||');
        formData.append('tag', tagsToSubmit);
        flag = true;
      }
      
      if (bookFile.value!=undefined) {
    
        const file = bookFile.value[0];
        if (file) {  
          const blob = new Blob([file.raw], { type: file.raw.type});
          formData.append('cover',blob,file.name)
          flag=true
        }
      }
      if (flag) {
        formData.append('id', currentBook.value.id);
        await proxy.$http.post('/api/book/update', formData, {
          headers: { 'Content-Type': 'multipart/form-data' },
        }).then(response => {
          ElMessage.success('修改成功');
        }).catch(error => {
          ElMessage.error('修改失败');
        });
      } else {
        ElMessage.info('没有任何更改');
      }
    } else {
      ElMessage.error('请检查表单填写');
    }
  });
};


//作品删除
const confirmDelete = (book) => {
  ElMessageBox.confirm('确定要删除这个作品吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
        const formData = new FormData();
        console.log('33333',book.id)
        formData.append('book_id',book.id)
        await proxy.$http.post("/api/book/delete",formData,
          {
            headers: {
             'Content-Type': 'multipart/form-data'
            }
          }
         ).then(res=>{
        const bookIndex = books.value.findIndex(b => b.id === book.id);
        if (bookIndex !== -1) {
          books.value.splice(bookIndex, 1);
        }
        ElMessage.success(res.data);
        console.log(res)
        isEditBookDialogVisible.value=false
      })
  });
};


onMounted(() => {
    try {
      getBooks_by_write(writer_account.value, proxy)
    } catch (error) {
        console.error('Error fetching carousel books:', error);
    }
});
</script>

<style scoped>
.main-box { /* 容器样式调整 */
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.book-table { /* 表格样式调整 */
  max-height: 450px;
}
.edit-box { /* 编辑按钮盒子样式 */
  display: flex;
  align-items: center;
  width: 160px;
}
.select-box { /* 选择章节盒子样式 */
  display: flex;
  margin-bottom: 10px;
  gap: 20px;
}
.form-box { /* 表单盒子样式 */
  width: 60%;
}
.book-cover { /* 书籍封面图片样式 */
  width: 115px;
  height: 150px;
  margin-right: 20px;
  border-radius: 3%;
}
.book-cover:hover{
  cursor: pointer;
}
.book-details { /* 书籍详细信息样式 */
  display: flex;
  width:50%;
  height: 100%;
  border: 1px solid rgba(255, 255, 255, 0.6);
  box-shadow: 2px 1px 19px rgba(0, 0, 0, 0.1);
  border-radius: 3%;
  flex-direction: column;
  margin-left: 1%;
}
.book-box{
  margin-left: 2%;
  margin-top: 2%;
  height: 300px;
  width: 100%;
}
.chapter-select { /* 章节选择下拉框样式 */
  width: 30%;
}
.is-disabled { /* 禁用状态样式 */
  cursor: not-allowed;
}
.tag-group{
  display: flex;
  flex-wrap: wrap;
  row-gap: 4px;
}
.tag-group .el-tag--plain {
    color: black;
    font-size: 12px;
    border-color: #efefef;
    margin-right: 10px;
    cursor: pointer;
}
.tag-group .active {
    color: #3e79ff;
    background-color: #ecf5ff;
    border: 1px solid #9eb5ed;
}
</style>